<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row>
              <el-col :span="6">
                <el-form-item label="姓名" prop="nickname">
                  <el-input v-model="queryParams.nickname" placeholder="请输入用户姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="上级推广员" prop="bindUserName" label-width="110">
                  <el-input v-model="queryParams.bindUserName" placeholder="请输入上级推广员姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间" style="width: 308px">
                  <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="推广资格" prop="status">
                  <el-select v-model="queryParams.status" placeholder="请选择推广资格" clearable>
                    <el-option value="0" label="禁用" />
                    <el-option value="1" label="启用" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lawyer:brokerageUser:add']">新增</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['lawyer:brokerageUser:edit']">修改</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['lawyer:brokerageUser:remove']">删除</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['lawyer:brokerageUser:export']">导出</el-button>-->
<!--          </el-col>-->
<!--          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
      </template>

      <el-table v-loading="loading" :data="brokerageUserList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键ID" align="center" prop="brokerageUserId" v-if="false" />
        <el-table-column label="姓名" align="center" prop="nickname" />
        <el-table-column label="头像" align="center" prop="avatar">
          <template #default="scope">
            <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" :preview-teleported="true"
                      :lazy="true" fit="cover" style="width: 50px; height:50px; "/>
          </template>
        </el-table-column>
        <el-table-column label="推广资格" align="center" prop="status" width="140">
          <template #default="scope">
            <el-text v-if="scope.row.status === '1'">启用</el-text>
            <el-text type="danger" v-else>禁用</el-text>
          </template>
        </el-table-column>
        <el-table-column label="推广人数" align="center" prop="userCount" />
        <el-table-column label="推广订单数量" align="center" prop="orderCount" />
        <el-table-column label="推广订单金额" align="center" prop="orderAmount">
          <template #default="scope">
            <el-text>{{ scope.row.orderAmount * 0.01 }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="已提现金额" align="center" prop="withdrawAmount">
          <template #default="scope">
            <el-text>{{ scope.row.withdrawAmount * 0.01 }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="已提现次数" align="center" prop="withdrawCount" />
        <el-table-column label="余额" align="center" prop="balanceFee">
          <template #default="scope">
            <el-text>{{ scope.row.balanceFee * 0.01 }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="冻结中佣金" align="center" prop="frozenAmount">
          <template #default="scope">
            <el-text>{{ scope.row.frozenAmount * 0.01 }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="brokerageTime" width="180" />
        <el-table-column label="上级推广员" align="center" prop="bindUserName" />
<!--        <el-table-column label="绑定时间" align="center" prop="bindUserTime" width="180" />-->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="启用推广资格" placement="top" v-if="scope.row.status === '0'">
              <el-button link type="primary" icon="CircleCheck" @click="handleChangeStatus(scope.row)" v-hasPermi="['brokerage:user:active']"></el-button>
            </el-tooltip>
            <el-tooltip content="禁用推广资格" placement="top" v-if="scope.row.status === '1'">
              <el-button link type="danger" icon="Remove" @click="handleChangeStatus(scope.row)" v-hasPermi="['brokerage:user:inactive']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改分销员对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="brokerageUserFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信用户ID" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入微信用户ID" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="form.avatar" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="邀请码" prop="brokerageCode">
          <el-input v-model="form.brokerageCode" placeholder="请输入邀请码" />
        </el-form-item>
        <el-form-item label="推广人数" prop="userCount">
          <el-input v-model="form.userCount" placeholder="请输入推广人数" />
        </el-form-item>
        <el-form-item label="推广订单数量" prop="orderCount">
          <el-input v-model="form.orderCount" placeholder="请输入推广订单数量" />
        </el-form-item>
        <el-form-item label="推广订单金额，单位分" prop="orderAmount">
          <el-input v-model="form.orderAmount" placeholder="请输入推广订单金额，单位分" />
        </el-form-item>
        <el-form-item label="已提现金额，单位分" prop="withdrawAmount">
          <el-input v-model="form.withdrawAmount" placeholder="请输入已提现金额，单位分" />
        </el-form-item>
        <el-form-item label="已提现次数" prop="withdrawCount">
          <el-input v-model="form.withdrawCount" placeholder="请输入已提现次数" />
        </el-form-item>
        <el-form-item label="成为推广员时间" prop="brokerageTime">
          <el-date-picker clearable
                          v-model="form.brokerageTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择成为推广员时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上级推广员ID" prop="bindUserId">
          <el-input v-model="form.bindUserId" placeholder="请输入上级推广员ID" />
        </el-form-item>
        <el-form-item label="上级推广员姓名" prop="bindUserName">
          <el-input v-model="form.bindUserName" placeholder="请输入上级推广员姓名" />
        </el-form-item>
        <el-form-item label="推广员绑定时间" prop="bindUserTime">
          <el-date-picker clearable
                          v-model="form.bindUserTime"
                          type="datetime"
                          value-format="YYYY-MM-DD HH:mm:ss"
                          placeholder="请选择推广员绑定时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BrokerageUser" lang="ts">
import { listBrokerageUser, getBrokerageUser, delBrokerageUser, addBrokerageUser, updateBrokerageUser, activeBrokerageUser, inactiveBrokerageUser } from '@/api/brokerage/user';
import { BrokerageUserVo, BrokerageUserQuery, BrokerageUserForm } from '@/api/brokerage/user/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const brokerageUserList = ref<BrokerageUserVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const brokerageUserFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BrokerageUserForm = {
  brokerageUserId: undefined,
  wxUserId: undefined,
  nickname: undefined,
  avatar: undefined,
  brokerageCode: undefined,
  status: undefined,
  userCount: undefined,
  orderCount: undefined,
  orderAmount: undefined,
  withdrawAmount: undefined,
  withdrawCount: undefined,
  brokerageTime: undefined,
  bindUserId: undefined,
  bindUserName: undefined,
  bindUserTime: undefined,
};
const data = reactive<PageData<BrokerageUserForm, BrokerageUserQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: undefined,
    nickname: undefined,
    bindUserName:undefined,
    params: {
    }
  },
  rules: {
    brokerageUserId: [
      { required: true, message: "主键ID不能为空", trigger: "blur" }
    ],
    wxUserId: [
      { required: true, message: "微信用户ID不能为空", trigger: "blur" }
    ],
    nickname: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" }
    ],
    avatar: [
      { required: true, message: "头像不能为空", trigger: "blur" }
    ],
    brokerageCode: [
      { required: true, message: "邀请码不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "推广资格(0停用，1启用）不能为空", trigger: "change" }
    ],
    userCount: [
      { required: true, message: "推广人数不能为空", trigger: "blur" }
    ],
    orderCount: [
      { required: true, message: "推广订单数量不能为空", trigger: "blur" }
    ],
    orderAmount: [
      { required: true, message: "推广订单金额，单位分不能为空", trigger: "blur" }
    ],
    withdrawAmount: [
      { required: true, message: "已提现金额，单位分不能为空", trigger: "blur" }
    ],
    withdrawCount: [
      { required: true, message: "已提现次数不能为空", trigger: "blur" }
    ],
    brokerageTime: [
      { required: true, message: "成为推广员时间不能为空", trigger: "blur" }
    ],
    bindUserId: [
      { required: true, message: "上级推广员ID不能为空", trigger: "blur" }
    ],
    bindUserName: [
      { required: true, message: "上级推广员姓名不能为空", trigger: "blur" }
    ],
    bindUserTime: [
      { required: true, message: "推广员绑定时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询分销员列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBrokerageUser(proxy?.addDateRange(queryParams.value, dateRange.value));
  brokerageUserList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  brokerageUserFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BrokerageUserVo[]) => {
  ids.value = selection.map(item => item.brokerageUserId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加分销员';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: BrokerageUserVo) => {
  reset();
  const _brokerageUserId = row?.brokerageUserId || ids.value[0];
  const res = await getBrokerageUser(_brokerageUserId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改分销员';
}

/** 提交按钮 */
const submitForm = () => {
  brokerageUserFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.brokerageUserId) {
        await updateBrokerageUser(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addBrokerageUser(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BrokerageUserVo) => {
  const _brokerageUserIds = row?.brokerageUserId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delBrokerageUser(_brokerageUserIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
}

/** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download('lawyer/brokerageUser/export', {
//     ...queryParams.value
//   }, `BrokerageUser_${new Date().getTime()}.xlsx`)
// }

const handleChangeStatus = async (row?: BrokerageUserVo) => {
  const text = row.status === '0' ? '启用' : '禁用';
  const _brokerageUserIds = row?.brokerageUserId;
  await proxy?.$modal.confirm(`确认要${text}${row.nickname}的推广资格吗`).finally(() => loading.value = false);
  if (row.status === '0') {
    await activeBrokerageUser(_brokerageUserIds);
  }else {
    await inactiveBrokerageUser(_brokerageUserIds);
  }
  proxy?.$modal.msgSuccess(`${text}成功`);
  await getList();
};
onMounted(() => {
  getList();
});
</script>
